package org.grow.leavejpa.service;


import com.querydsl.jpa.impl.JPAQueryFactory;
import org.grow.leavejpa.dao.UserInfoJpa;
import org.grow.leavejpa.entity.*;
import org.grow.leavejpa.entity.QRoleInfo;
import org.grow.leavejpa.entity.QUserInfo;
import org.grow.leavejpa.entity.QUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-6-7
 */
@Service
public class UserInfoService implements UserDetailsService {

    @Autowired
    private UserInfoJpa userInfoJpa;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    QUserInfo u = QUserInfo.userInfo;
    QUserRole ur = QUserRole.userRole;
    QRoleInfo r = QRoleInfo.roleInfo;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoJpa.findByUsername(s);
//        if (userInfo == null)
//         :1 根据username查询roles
        List<RoleInfo> roleInfos = jpaQueryFactory.
                select(r).from(u)
                .leftJoin(ur).on(u.userId.eq(ur.userFk))
                .leftJoin(r).on(ur.roleFk.eq(r.roleId))
                .where(u.username.eq(s))
//                .where(Expressions.booleanTemplate("{0} = {1}","zhangjiu001",u.username))
                .fetch();

        userInfo.setAuthorities(roleInfos);

        System.out.println("数据库查询到的: "+userInfo);
        return userInfo;
    }
}
